package com.wts.client;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.json.JSONObject;

import com.wts.client.https.HttpUtils;
import com.wts.client.utils.WtcJsonMap;

/**
 * 用戶机构岗位接口
 * 
 * @author macpl
 *
 */
public class WtsAuthClient {
	private String secret;
	private String operatorLoginname;
	private String operatorPassword;
	private String baseUrl;
	private Map<String, String> urls;

	private String interflag = "/api/auth";

	public WtsAuthClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
	}

	/**
	 * @param baseUrl
	 * @param secret
	 * @param operatorLoginname
	 * @param operatorPassword
	 * @param apiPath           接口相对地址如 "/api/auth"或"/api"
	 */
	public WtsAuthClient(String baseUrl, String secret, String operatorLoginname, String operatorPassword,
			String apiPath) {
		super();
		this.secret = secret;
		this.baseUrl = baseUrl;
		this.operatorLoginname = operatorLoginname;
		this.operatorPassword = operatorPassword;
		this.interflag = apiPath;
	}

	private void initBaseParas(Map<String, String> para) {
		para.put("operatorLoginname", operatorLoginname);
		para.put("operatorPassword", operatorPassword);
		para.put("secret", secret);
	}

	/**
	 * 校驗接口執行情況
	 * 
	 * @param url
	 * 
	 * @param json
	 */
	private void validateBackJson(String url, JSONObject json) {
		String state = json.get("STATE").toString();
		if (state.equals("1")) {
			throw new RuntimeException(json.get("MESSAGE").toString() + " by " + url);
		}
	}

	private Map<String, String> getApiUrls() {
		urls = new HashMap<>();
		urls.put("getPost", baseUrl + interflag + "/get/posts.do");
		urls.put("postPost", baseUrl + interflag + "/post/post.do");
		urls.put("putPost", baseUrl + interflag + "/put/post.do");
		urls.put("deletePost", baseUrl + interflag + "/delete/post.do");
		urls.put("bindPost", baseUrl + interflag + "/bind/posts.do");
		urls.put("getUser", baseUrl + interflag + "/get/user.do");
		return urls;
	}

	/**
	 * 服务是否可用
	 * 
	 * @return
	 */
	public boolean isLive(boolean throwExceptionAble) {
		Map<String, String> data = new HashMap<String, String>();
		data.put("secret", secret);
		data.put("operatorLoginname", operatorLoginname);
		data.put("operatorPassword", operatorPassword);
		// -----------
		data.put("loginname", operatorLoginname);
		JSONObject backData = HttpUtils.httpPost(getApiUrls().get("getUser"), data);
		if (!backData.has("STATE") || backData.getInt("STATE") != 0) {
			if (throwExceptionAble) {
				throw new RuntimeException(backData.toString());
			} else {
				return false;
			}
		}
		return true;
	}

	/**
	 * 查询远程岗位
	 * 
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid
	 * @return
	 */
	public List<WtcJsonMap> getRemotePosts(String sourceflag) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("sourceflag", sourceflag);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getPost"), para);
		validateBackJson(getApiUrls().get("getPost"), json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		if (wjm.getList("DATA").size() > 0) {
			List<WtcJsonMap> wjms = wjm.getList("DATA");
			return wjms;
		} else {
			return null;
		}
	}

	/**
	 * 查询远程岗位
	 * 
	 * @param sourceid 来源id
	 * @return
	 */
	public WtcJsonMap getRemotePost(String sourceid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		para.put("sourceflag", sourceid);
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("getPost"), para);
		validateBackJson(getApiUrls().get("getPost"), json);
		WtcJsonMap wjm = new WtcJsonMap(json.toMap());
		if (wjm.getList("DATA").size() > 0) {
			List<WtcJsonMap> wjms = wjm.getList("DATA");
			return wjms.get(0);
		} else {
			return null;
		}
	}

//	urls.put("postPost", baseUrl + "/post/post.do");

	/**
	 * 创建远程岗位角色
	 * 
	 * @param sourceid 来源id,一般为来源系统的flag+来源系统id
	 * @param orgappid 组织机构的appid(可空)
	 * @param name     岗位名称
	 * @param extendis 作用范围1:含子机构,0：仅仅当前机构,2：所有机构
	 * @return
	 */
	public void creatRemotePost(String sourceid, String orgappid, String name, String extendis) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		if (StringUtils.isNotBlank(orgappid)) {
			para.put("orgappid", orgappid);
		}
		if (StringUtils.isNotBlank(name)) {
			para.put("name", name);
		} else {
			throw new RuntimeException("name is null");
		}
		if (StringUtils.isNotBlank(extendis)) {
			para.put("extendis", extendis);
		} else {
			throw new RuntimeException("extendis is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("postPost"), para);
		validateBackJson(getApiUrls().get("postPost"), json);
	}

	/**
	 * 修改更新岗位
	 * 
	 * @param sourceid 来源id 必填
	 * @param name     可空
	 * @param extendis 可空 作用范围1:含子机构,0：仅仅当前机构,2：所有机构
	 */
	public void editRemotePost(String sourceid, String name, String extendis) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		if (StringUtils.isNotBlank(name)) {
			para.put("name", name);
		}
		if (StringUtils.isNotBlank(extendis)) {
			para.put("extendis", extendis);
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("putPost"), para);
		validateBackJson(getApiUrls().get("putPost"), json);
	}

	/**
	 * 删除远程岗位
	 * 
	 * @param sourceid 来源id 必填
	 */
	public void delRemotePost(String sourceid) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (StringUtils.isNotBlank(sourceid)) {
			para.put("sourceid", sourceid);
		} else {
			throw new RuntimeException("sourceid is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("deletePost"), para);
		validateBackJson(getApiUrls().get("deletePost"), json);
	}

	/**
	 * 绑定人员到岗位
	 * 
	 * @param sourceids  可以为空，为空时清楚用户的所有岗位（匹配来源前缀）
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid，在绑定前会删除匹配该来源的全部人员岗位
	 * @param loginname  绑定到的用户登录名
	 */
	public void bindRemotePost(String sourceids, String sourceflag, String loginname) {
		List<String> ids = new ArrayList<String>();
		ids.add(sourceids);
		bindRemotePost(ids, sourceflag, loginname);
	}

	/**
	 * 绑定人员到岗位
	 * 
	 * @param sourceids  可以为空，为空时清楚用户的所有岗位（匹配来源前缀）
	 * @param sourceflag 来源前缀，将匹配以sourceflag开头的sourceid，在绑定前会删除匹配该来源的全部人员岗位
	 * @param loginname  绑定到的用户登录名
	 */
	public void bindRemotePost(List<String> sourceids, String sourceflag, String loginname) {
		Map<String, String> para = new HashMap<String, String>();
		initBaseParas(para);
		if (sourceids != null) {
			String ids = null;
			for (String id : sourceids) {
				if (ids == null) {
					ids = id;
				} else {
					ids = ids + "," + id;
				}
			}
			para.put("sourceids", ids);
		}
		if (StringUtils.isNotBlank(sourceflag)) {
			para.put("sourceflag", sourceflag);
		} else {
			throw new RuntimeException("sourceflag is null");
		}
		if (StringUtils.isNotBlank(loginname)) {
			para.put("loginname", loginname);
		} else {
			throw new RuntimeException("loginname is null");
		}
		JSONObject json = HttpUtils.httpPost(getApiUrls().get("bindPost"), para);
		validateBackJson(getApiUrls().get("bindPost"), json);
	}
}
